package ks.client.controllers.requests;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import ks.client.UserContext;
import ks.client.gui.UMGUI3;
import ks.client.lobby.Lobby;
import ks.framework.common.Message;
import ks.framework.interfaces.IProcessMessage;
import ks.managers.user.User;
import ks.managers.user.UserManager;

/**
 * The controller for the account-update request.
 * 
 * @author Christopher Page
 */
public class AccountUpdateController implements IProcessMessage {

	/** In case we need to process something. */
	Lobby lobby;
	
	/** Construct controller with lobby. */
	public AccountUpdateController(Lobby lobby) {
		this.lobby = lobby;
	}

	/**
	 * Client has received account-update message. Process it.
     * 
	 * @param m
	 * @return
	 */
	public boolean process(Message m) {
		// Get context
		UserContext context = lobby.getUserContext();
		
		// get UserManager instance
		UserManager um = context.getUserManager();
		
		//get UserManager gui
		UMGUI3 gui = lobby.getUMGUI3();
		
		// extract information from the message
		Node accUpdate = m.contents();
		NamedNodeMap nnp = accUpdate.getAttributes();
		Node playerNode = nnp.getNamedItem("player");
		Node iconNode = nnp.getNamedItem("icon");
		Node ratingNode = nnp.getNamedItem("rating");
		
		// get user in update message, return false if doesn't exist
		User u;
		if (playerNode == null) {
			return false;
		}
		else {
			u = um.getUser(playerNode.getNodeValue());
		}
		if (u == null) {
			return false;
		}
		
		// set user icon if provided
		if (iconNode != null) {
			u.setIconName(iconNode.getNodeValue());
		}
		
		// set user rating if provided
		if (ratingNode != null) {
			u.setRating(Integer.parseInt(ratingNode.getNodeValue()));
		}
		
		gui.refreshTable();
		
		System.err.println("[AccountUpdateController] Note: code for gui update needed.");
		
		// success
		return true;
	}
}
